<template>
  <div class="comment">
    <div class="wrap">

        <div class="info">
            <div class="label">课堂表现评分</div>
            <div class="rating">
                <div class="rating-label">请对学生的课堂表现进行评分：</div>
                <van-rate
                    v-model="params.rating"
                    :size="28"
                    color="#ffd21e"
                    void-color="#c8c9cc"
                    void-icon="star"
                    :count="5"
                    @change="onRatingChange"
                />
                <div class="rating-text">
                    {{ getRatingText(params.rating) }}
                </div>
            </div>
        </div>

        <div class="info">
            <div class="label">课堂照片</div>
            <div class="remark">
                <van-uploader
                    :after-read="afterRead"
                    :max-count="6"
                    v-model="params.files"
                    multiple
                    :before-read="beforeRead"
                />
            </div>
        </div>



        <div class="info">
            <div class="label">
                学生评价
                <div class="ai-parse-btn-wrap">
                    <van-button
                        size="small"
                        type="primary"
                        @click="triggerAiAnalysis"
                        :loading="aiAnalyzing"
                        :disabled="params.files.length === 0"
                        class="ai-button"
                    >
                        <!-- <span class="ai-icon">🤖</span> -->
                        AI解析
                    </van-button>
                    <!-- <van-button
                        v-if="aiAnalysisResult"
                        size="small"
                        plain
                        type="info"
                        @click="editAiResult"
                        class="edit-button"
                    >
                        编辑
                    </van-button> -->
                </div>
            </div>
            <div class="remark">
                <van-field type="textarea" placeholder="请输入评价" v-model="params.remarks" :autosize="{minHeight: 80}"/>
            </div>
        </div>



        <!-- AI解析编辑弹窗 -->
        <van-popup v-model="showEditPopup" position="bottom" :style="{ height: '60%' }">
            <div class="edit-popup">
                <div class="popup-header">
                    <span>编辑AI解析结果</span>
                    <van-button size="small" type="primary" @click="saveEditedResult">保存</van-button>
                </div>
                <div class="popup-content">
                    <van-field
                        type="textarea"
                        placeholder="请编辑AI解析结果..."
                        v-model="editingAiResult"
                        :autosize="{minHeight: 200}"
                    />
                </div>
            </div>
        </van-popup>

        <!-- 销课弹窗 - 使用公共组件 -->
        <CancelClassDialog
            :visible="showCancelDialog"
            :student-info="params.item"
            :course-params="{
                courseStartime: routeParams.courseStartime,
                counrseEndtime: routeParams.counrseEndtime,
                teacherNumber: $route.params.teacherNumber
            }"
            @update:visible="showCancelDialog = $event"
            @confirm="handleCancelClassConfirm"
            @close="handleCancelClassClose"
        />
    </div>
    <div class="btn_wrap">
        <div class="btn mainBgBtnColor" @click="submit">提交评价</div>
    </div>
  </div>
</template>

<script>
import { Field, Uploader, Button, Popup, Toast, Rate } from 'vant';
import CancelClassDialog from '@/components/CancelClassDialog.vue';
export default {
    components: {
        'van-uploader': Uploader,
        'van-field': Field,
        'van-button': Button,
        'van-popup': Popup,
        'van-rate': Rate,
        CancelClassDialog
    },
    data() {
        return {
            params: {
                item: {},
                remarks: '',
                files: [],
                rating: 0 // 课堂表现评分，0表示未评分
            },
            routeParams: {},
            // AI解析相关数据
            showAiAnalysis: false,
            aiAnalysisResult: '',
            showEditPopup: false,
            editingAiResult: '',
            currentAnalyzingFile: null,
            aiAnalyzing: false,
            // 销课相关数据
            showCancelDialog: false,
            hasCanceledClass: false, // 标记是否已经销课
            cancelData: null // 保存销课数据
        }
    },
    created() {
        const {classId,courseId, courseNumber, counrseEndtime, courseStartime, item} = this.$route.params
        this.routeParams = { classId,courseId, courseNumber, counrseEndtime, courseStartime }
        this.params = {
            item,
            remarks: '',
            files: [],
            rating: 0
        };
        if (item.evaluationId) this.getData();
    },
    beforeDestroy() {
        this.$route.params.classId = this.routeParams.classId
        this.$route.params.courseId = this.routeParams.courseId
        this.$route.params.courseNumber = this.routeParams.courseNumber
        this.$route.params.courseStartime = this.routeParams.courseStartime
        this.$route.params.counrseEndtime = this.routeParams.counrseEndtime
    },
    methods: {
        getData() {
            this.$http.getEnvDetail({pjId: this.params.item.evaluationId}).then(res => {
                console.log(res, 'res')
                this.params.remarks = res.data.result.evaluate;
                // 设置课堂表现评分，将字符串转换为数字
                if (res.data.result.rating) {
                    this.params.rating = parseInt(res.data.result.rating) || 0;
                }
                // 处理enclosure为空的情况
                const enclosure = res.data.result.enclosure;
                if (!enclosure) {
                    this.params.files = [];
                } else {
                    this.params.files = enclosure.split(',').filter(item => item.trim()).map(item => {
                        // 检查item是否已经是完整的URL
                        const isFullUrl = item.startsWith('http://') || item.startsWith('https://');
                        return {
                            url1: item,
                            url: isFullUrl ? item : item
                        }
                    })
                }
            })
        },
        // 文件上传前检查
        beforeRead(file) {
            const isImage = file.type.includes('image/');
            if (!isImage) {
                Toast('请上传图片文件');
                return false;
            }
            const isLt5M = file.size / 1024 / 1024 < 5;
            if (!isLt5M) {
                Toast('上传图片大小不能超过 5MB!');
                return false;
            }
            return true;
        },
        afterRead(e) {
            console.log(e.file, 'eee')
            let formData = new FormData();
            formData.append('file', e.file)
            this.$http.uploadFile(formData).then(res => {
                if (res.data.code === 200) {
                    res.data.result.url1 = res.data.result.url;
                    // 检查返回的URL是否已经是完整的URL
                    const isFullUrl = res.data.result.url.startsWith('http://') || res.data.result.url.startsWith('https://');
                    res.data.result.url = isFullUrl ? res.data.result.url : res.data.result.url;
                    this.params.files.push(res.data.result)
                    this.params.files = this.params.files.filter(item => item.url)
                    console.log(this.params.files, 'this.params.files')
                } else {
                    this.$toast('上传失败')
                }
            })
        },
        // 手动触发AI解析
        triggerAiAnalysis() {
            if (this.params.files.length === 0) {
                Toast('请先上传图片');
                return;
            }

            // 选择最新上传的图片进行解析
            const latestFile = this.params.files[this.params.files.length - 1];
            this.analyzeImageWithAI(latestFile);
        },
        // AI图片解析
        analyzeImageWithAI(fileInfo) {
            Toast.loading({
                message: 'AI解析中...',
                forbidClick: true,
                duration: 0
            });

            this.currentAnalyzingFile = fileInfo;

            // 构建请求数据，按照示例格式
            // 修改：根据所有已上传的图片构建imageUrls数组
            const requestData = {
                imageUrls: this.params.files.map(file => file.url1), // 使用所有已上传图片的url1
                videoUrls: [],
                remark: "",
                classId: this.routeParams.classId, // 添加班级ID
                courseId: this.params.item.courseId, // 添加课程ID
                studentId: this.params.item.studentId // 添加学生ID
            };

            // 调用新的AI解析接口
            this.$http.analyzeImages(requestData).then(res => {
                Toast.clear();
                if (res.data.code === 200) {
                    // 格式化返回的AI解析结果
                    const formattedResult = this.formatAiAnalysisResult(res.data);
                    this.aiAnalysisResult = formattedResult;
                    // 直接将AI解析结果应用到评价输入框
                    this.params.remarks = formattedResult;
                    Toast.success('AI解析完成，已自动应用到评价');
                } else {
                    Toast('AI解析失败：' + (res.data.message || '未知错误'));
                }
            }).catch(err => {
                Toast.clear();
                console.error('AI解析错误:', err);
                // 如果后端接口未实现，使用模拟数据
                this.useMockAiAnalysis(fileInfo);
            })
        },
        // 格式化AI解析结果
        formatAiAnalysisResult(responseData) {
            try {
                // 如果result字段是字符串且包含JSON，尝试解析
                if (typeof responseData.result === 'string') {
                    const parsedResult = JSON.parse(responseData.result);
                    if (parsedResult && parsedResult.result) {
                        // 返回格式化后的结果
                        return this.formatTextContent(parsedResult.result);
                    }
                }

                // 如果直接返回了结果对象
                if (responseData.result && responseData.result.result) {
                    return this.formatTextContent(responseData.result.result);
                }

                // 如果以上都不符合，返回原始结果
                return this.formatTextContent(responseData.result || responseData.data || 'AI解析完成，但未返回具体内容');
            } catch (error) {
                console.error('解析AI结果失败:', error);
                // 如果解析失败，返回原始结果
                return this.formatTextContent(responseData.result || responseData.data || 'AI解析完成，但未返回具体内容');
            }
        },

        // 格式化文本内容，处理转义字符和格式
        formatTextContent(text) {
            if (!text) return '';

            // 替换转义字符
            let formattedText = text
                .replace(/\\n/g, '\n')  // 替换 \n 为换行
                .replace(/\\t/g, '  ')  // 替换 \t 为两个空格
                .replace(/\\"/g, '"')   // 替换 \" 为 "
                .replace(/\\\\/g, '\\'); // 替换 \\ 为 \

            // 添加适当的段落间距
            formattedText = formattedText
                .replace(/\n\n+/g, '\n\n')  // 多个换行替换为两个换行
                .replace(/### /g, '\n### ')  // 为标题添加前导换行
                .replace(/\n### /g, '\n\n### '); // 为标题添加更多间距

            return formattedText.trim();
        },
        // 使用模拟AI解析（当后端接口未实现时）
        useMockAiAnalysis(fileInfo) {
            const mockResults = [
                '该学生在本节课中表现积极，课堂参与度高，能够认真完成老师布置的任务。作业书写工整，思路清晰，展现了良好的学习态度。',
                '学生课堂表现良好，能够主动回答问题，与同学互动积极。但在某些知识点上还需要加强理解，建议课后多练习相关题目。',
                '本节课学生注意力集中，能够跟上老师的教学节奏。作业完成质量较高，体现了对知识点的掌握程度。继续保持！',
                '学生在本节课中展现了较强的学习能力，能够举一反三。课堂笔记记录详细，课后复习认真，学习习惯良好。',
                '该生学习态度端正，能够按时完成作业。在小组讨论中表现活跃，能够与同学良好合作。建议加强独立思考能力。'
            ];

            const randomResult = mockResults[Math.floor(Math.random() * mockResults.length)];
            this.aiAnalysisResult = randomResult;
            // 直接将AI解析结果应用到评价输入框
            this.params.remarks = randomResult;
            Toast.success('AI解析完成（模拟数据），已自动应用到评价');
        },
        // 编辑AI解析结果
        editAiResult() {
            this.editingAiResult = this.aiAnalysisResult;
            this.showEditPopup = true;
        },
        // 保存编辑后的结果
        saveEditedResult() {
            if (this.editingAiResult.trim()) {
                this.aiAnalysisResult = this.editingAiResult;
                // 将编辑后的结果直接应用到评价输入框
                this.params.remarks = this.editingAiResult;
                this.showEditPopup = false;
                Toast.success('编辑已保存并应用到评价');
            } else {
                Toast('请输入有效内容');
            }
        },
        submit() {
            console.log('点击提交按钮', this.params.item);
            console.log('hasCanceledClass:', this.hasCanceledClass);
            console.log('marketingState:', this.params.item.marketingState);

            // 验证课堂表现评分为必输项
            if (this.params.rating === 0) {
                Toast('请对课堂表现进行评分');
                return;
            }

            // 验证学生评价和课堂照片必须至少有一个有值
            if (!this.params.remarks.trim() && this.params.files.length === 0) {
                Toast('请填写学生评价或上传课堂照片');
                return;
            }

            // 检查 params.item 对象是否存在 marketingState 属性
            const marketingState = this.params.item.marketingState;
            console.log('处理后的 marketingState:', marketingState);

            // 检查是否已经销课，如果没有且 marketingState 不等于0则弹出销课弹窗
            if (!this.hasCanceledClass && marketingState != '0') {
                console.log('需要销课，显示销课弹窗');
                this.showCancelDialog = true;
                console.log('showCancelDialog 设置为:', this.showCancelDialog);
                return;
            }

            console.log('不需要销课或已销课，直接提交评价');
            // 如果已经销课或不需要销课，直接提交评价
            this.submitEvaluation();
        },

        // 销课弹窗确认事件
        handleCancelClassConfirm(cancelData) {
            // 保存销课数据，用于后续提交评价
            this.cancelData = cancelData;
            // 标记为已销课，并自动提交评价
            this.hasCanceledClass = true;
            this.submitEvaluation();
        },

        // 销课弹窗关闭事件
        handleCancelClassClose() {
            // 弹窗关闭，不做任何操作
            console.log('销课弹窗已关闭');
        },

        // 评分变化处理
        onRatingChange(value) {
            console.log('评分变化:', value);
            this.params.rating = value;
        },

        // 获取评分对应的文字描述
        getRatingText(rating) {
            const ratingTexts = {
                0: '请选择评分',
                1: '有待改进',
                2: '一般',
                3: '良好',
                4: '优秀',
                5: '非常出色'
            };
            return ratingTexts[rating] || '请选择评分';
        },

        // 提交评价
        submitEvaluation() {
            let query = {
                ...this.params.item,
                id: this.params.item.evaluationId ? this.params.item.evaluationId : '',
                studentNumber: this.params.item.studentId,
                courseNumber: this.params.item.courseId,
                enclosure: this.params.files.map(item => item.url1).join(','),
                evaluate: this.params.remarks,
                rating: this.params.rating, // 添加评分数据
                startTime: this.routeParams.courseStartime,
                endTime: this.routeParams.counrseEndtime,
                // 无论是否调用销课组件，都包含销课相关字段
                cancelReason: this.cancelData?.cancelReason || '',
                xknumber: this.cancelData?.xknumber || 1
            };

            Toast.loading({
                message: '提交评价中...',
                forbidClick: true,
                duration: 0
            });

            this.$http.submitEnv(query).then(res => {
                Toast.clear();
                console.log(res,'res')
                if (res.data.code === 200) {
                    this.$toast('评价成功')
                    setTimeout(() => {
                        this.params.remarks = '';
                        this.params.files = [];
                        this.cancelData = null; // 清空销课数据
                        this.$router.back();
                    }, 1500)
                } else {
                    this.$toast(`评价失败：${res.data.message}`)
                }
            }).catch(err => {
                Toast.clear();
                console.log(err, 'err')
                this.$toast(`评价失败：${err.data.message}`)
            })
        }
    }

}
</script>

<style lang="scss" scoped>
    .comment {
        width: 100%;
        height: 100%;
        color: #333;
        padding: 16px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        background-color: #f8f9fa;

        .wrap {
            flex: 1;
            overflow-y: auto;
            background: #fff;
            border-radius: 12px;
            padding: 16px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

            .info {
                display: flex;
                flex-direction: column;
                margin-bottom: 24px;
                padding: 16px;
                background: #fafafa;
                border-radius: 8px;
                border: 1px solid #f0f0f0;

                .label {
                    font-size: 16px;
                    font-weight: 600;
                    color: #1a1a1a;
                    margin-bottom: 12px;
                    display: flex;
                    align-items: center;

                    &::before {
                        content: '';
                        display: inline-block;
                        width: 4px;
                        height: 16px;
                        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                        border-radius: 2px;
                        margin-right: 8px;
                    }
                }

                .remark {
                    flex: 1;
                    white-space: normal;
                    overflow: hidden;

                    ::v-deep .van-field {
                        background: #fff;
                        border-radius: 6px;
                        border: 1px solid #e8e8e8;

                        .van-field__control {
                            min-height: 80px;
                            padding: 12px;
                            font-size: 14px;
                            line-height: 1.5;
                        }
                    }

                    ::v-deep .van-uploader {
                        .van-uploader__upload {
                            background: #f5f5f5;
                            border: 1px dashed #d9d9d9;
                            border-radius: 6px;
                        }

                        .van-uploader__preview-image {
                            border-radius: 6px;
                            overflow: hidden;
                        }
                    }
                }

                /* 评分区域样式 */
                .rating {
                    .rating-label {
                        font-size: 14px;
                        color: #666;
                        margin-bottom: 12px;
                    }

                    ::v-deep .van-rate {
                        margin-bottom: 8px;
                    }

                    .rating-text {
                        font-size: 14px;
                        color: #ff6b35;
                        font-weight: 500;
                        text-align: center;
                        padding: 8px 12px;
                        background: #fff8f6;
                        border-radius: 6px;
                        border: 1px solid #ffe8e1;
                        transition: all 0.3s ease;
                    }
                }
            }
        }

        .btn_wrap {
            padding: 16px;
            box-sizing: border-box;

            .btn {
                width: 100%;
                height: 48px;
                font-size: 16px;
                font-weight: 600;
                color: #fff;
                text-align: center;
                line-height: 48px;
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                border: none;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
                transition: all 0.3s ease;

                &:active {
                    transform: translateY(1px);
                    box-shadow: 0 2px 6px rgba(102, 126, 234, 0.3);
                }
            }
        }

        /* AI解析按钮样式 - 超链接样式 */
        .ai-parse-btn-wrap {
            display: flex;
            align-items: center;
            gap: 12px;

            .ai-button {
                font-size: 14px;
                padding: 10px;
                height: auto;
                line-height: 1.4;
                background: transparent;
                border: none;
                color: #1890ff;
                text-decoration: underline;
                box-shadow: none;
                transition: all 0.2s ease;

                &:hover {
                    color: #40a9ff;
                    text-decoration: underline;
                    transform: none;
                    box-shadow: none;
                }

                &:active {
                    color: #096dd9;
                    transform: none;
                    box-shadow: none;
                }

                &:disabled {
                    color: #c8c9cc;
                    background: transparent;
                    text-decoration: none;
                    transform: none;
                    box-shadow: none;
                }

                .ai-icon {
                    margin-right: 4px;
                    font-size: 14px;
                }
            }

            .edit-button {
                font-size: 14px;
                padding: 0;
                height: auto;
                line-height: 1.4;
                background: transparent;
                border: none;
                color: #52c41a;
                text-decoration: underline;
                box-shadow: none;
                transition: all 0.2s ease;

                &:hover {
                    color: #73d13d;
                    text-decoration: underline;
                }

                &:active {
                    color: #389e0d;
                }
            }
        }


        /* 编辑弹窗样式 */
        .edit-popup {
            height: 100%;
            display: flex;
            flex-direction: column;

            .popup-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 16px;
                border-bottom: 1px solid #e8e8e8;
                background-color: #fff;

                span {
                    font-size: 16px;
                    font-weight: 500;
                }
            }

            .popup-content {
                flex: 1;
                padding: 16px;
                background-color: #fff;

                ::v-deep .van-field__control {
                    min-height: 200px;
                }
            }
        }

    }
</style>
